/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.crystalrange.documents.web;

import org.crystalrange.BaseController;
import org.crystalrange.Message;
import org.crystalrange.documents.model.DocumentReferenceType;
import org.crystalrange.documents.service.DocumentReferenceTypeService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;

/**
 *
 * @author Krzysiek
 */
public class DocumentReferenceTypeController extends BaseController {
    
    private DocumentReferenceType documentReferenceType;
    private DocumentReferenceTypeService documentReferenceTypeService;

    public DocumentReferenceType getDocumentReferenceType() {
        return documentReferenceType;
    }

    public void setDocumentReferenceType(DocumentReferenceType documentReferenceType) {
        this.documentReferenceType = documentReferenceType;
    }

    public DocumentReferenceTypeService getDocumentReferenceTypeService() {
        return documentReferenceTypeService;
    }

    public void setDocumentReferenceTypeService(DocumentReferenceTypeService documentReferenceTypeService) {
        this.documentReferenceTypeService = documentReferenceTypeService;
    }
    
     public void onClick$toolbarbuttonDocumentReferenceTypeSave(Event event) throws Exception {
        this.documentReferenceTypeSave();
        
    }
    
    private void documentReferenceTypeSave() throws Exception {
    	if (this.documentReferenceType.getName() != null) {
    		this.documentReferenceTypeService.save(this.documentReferenceType);
    		this.sessionScope.put("CRYSTALRANGE_MESSAGE", new Message("Saved successfully!"));
    		Clients.evalJavaScript("window.history.back();");
		} else {
			this.message.setText("You must enter 'Reference Type Name'.");
            this.message.setIcon("/img/exclamation.png");
            this.binder.loadAll();
		}
    }
    
    
    @Override
    public void doAfterCompose(Component component) throws Exception {
        super.doAfterCompose(component);
        
        if (this.execution.getParameter("Id") != null) {
            this.documentReferenceType = this.documentReferenceTypeService.find(
                    Long.parseLong(this.execution.getParameter("Id")));
            this.labelTitle.setValue("Edit Document Reference Type");
        } else {
            this.documentReferenceType = this.documentReferenceTypeService.create(
                    SecurityContextHolder.getContext().getAuthentication().getName());
            this.labelTitle.setValue("Create Document Reference Type");
        }
        
        component.setAttribute("controller", this);
    }
}
